package com.firefly.service.command.mc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.firefly.dao.dao.mc.po.AgentPo;
import com.firefly.dao.dao.mc.po.McRolePermissionPo;
import com.firefly.dao.dao.mc.po.UserPo;
import com.firefly.dao.dao.mc.service.AgentService;
import com.firefly.dao.dao.mc.service.McRolePermissionService;
import com.firefly.dao.dao.mc.service.UserService;
import com.firefly.dao.assembler.mc.McUserAssembler;
import com.firefly.dao.dto.mc.McUserUpdateNickDto;
import com.firefly.dao.util.RedisUtils;
import com.firefly.dao.vo.mc.McLoginVo;
import com.firefly.util.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description:
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2023/2/9
 **/
@Service
public class McUserCommand {
    private final UserService userService;
    private final AgentService agentService;
    private final McRolePermissionService mcRolePermissionService;
    private final RedisUtils redisUtils;
    private final McUserAssembler mcUserAssembler;
    @Autowired
    public McUserCommand(UserService userService,AgentService agentService,McRolePermissionService mcRolePermissionService,RedisUtils redisUtils,McUserAssembler mcUserAssembler){
        this.userService = userService;
        this.agentService = agentService;
        this.mcRolePermissionService = mcRolePermissionService;
        this.redisUtils = redisUtils;
        this.mcUserAssembler = mcUserAssembler;
    }
    // 退出登录
    public Boolean logout(String userId){
        redisUtils.del("mc-token:" + userId);
        return true;
    }
    // 更新头像昵称
    public Boolean updateNickThumb(McUserUpdateNickDto request){
        UpdateWrapper<UserPo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",request.getId()).set("nickname",request.getNickname()).set("thumb",request.getThumb());
        return userService.update(updateWrapper);
    }
    // 登录&注册
    /*
    * 检查手机号与微信号是否是新用户，手机号为新用户->注册；老用户->登录；
    * 微信号是否绑定过其他手机号，否->绑定；是->解绑其他手机号同时绑定此手机号；
    * 没有做三级分销判断
    * */
    @Transactional
    public McLoginVo loginOrRegister(String phone,String openId) throws Exception {
        // 检查手机号是否是新用户，手机号为新用户->注册；老用户->登录；
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone).eq("del_flag",0).last("limit 1").orderByDesc("id");
        UserPo userPhone = userService.getOne(queryWrapper,false);
        // 微信号是否绑定过其他手机号，否->绑定；是->解绑其他手机号同时绑定此手机号；
        QueryWrapper<UserPo> queryWrapperOpenId = new QueryWrapper<>();
        queryWrapper.eq("openid",openId).eq("del_flag",0).last("limit 1").orderByDesc("id");
        UserPo userOpenid = userService.getOne(queryWrapperOpenId,false);
        UserPo detail = new UserPo();
        // 新用户
        if (userPhone == null){
            // 微信号绑定过其他
            if (userOpenid != null){
                this.unbindOpenid(openId);
            }
            // 保存新账户号
            UserPo entity = mcUserAssembler.getPo(phone,openId);
            userService.save(entity);
            detail = entity;
        } else {
            // 微信号与绑定的不同
            if (userPhone.getOpenid() != openId){
                this.unbindOpenid(openId);
                userPhone.setOpenid(openId);
                userService.updateById(userPhone);
            }
            detail = userPhone;
        }
        // 开始组装返回的信息,主要查有没有代理商权限，权限是什么
        QueryWrapper<AgentPo> queryWrapperAgent = new QueryWrapper<>();
        queryWrapperAgent.eq("phone",phone).eq("status",1).eq("del_flag",0).orderByDesc("id").last("limit 1");
        AgentPo agentPo = agentService.getOne(queryWrapperAgent,false);
        Integer roleId = agentPo != null ? agentPo.getAgentLevel() : 5;
        Integer agentId = agentPo != null ? agentPo.getId() : 0;
        QueryWrapper<McRolePermissionPo> queryWrapperRolePermission = new QueryWrapper<>();
        queryWrapperRolePermission.eq("role_id",roleId).select("url");
        List<Object> urls = mcRolePermissionService.listObjs(queryWrapperRolePermission);
        String username = (detail.getId()).toString();
        String token = JWTUtil.sign(username, 30 * 24, "mc-token");
        McLoginVo result = new McLoginVo();
        result.setId(detail.getId());
        result.setName(detail.getNickname());
        result.setPhone(detail.getPhone());
        result.setToken(token);
        result.setAgentId(agentId);
        result.setRoleId(roleId);
        result.setUrls(urls);
        // 开始存redis
        redisUtils.del("mc-token:" + username);
        redisUtils.set("mc-token:" + username, result, 30 * 24 * 3600);
        return result;
    }
    // 解绑微信号所有的用户
    public void unbindOpenid(String openId){
        UpdateWrapper<UserPo> updateWrapperOpenid = new UpdateWrapper<>();
        updateWrapperOpenid.eq("openid",openId).set("openid",null);
        userService.update(updateWrapperOpenid);
    }

}
